/*
 * List.cpp
 *
 *  Created on: 23/05/2010
 *      Author: prodrig
 */

#include "List.h"
#include "ListIterator.h"
#include <stdio.h>
#include <string>
#include <sstream>

using std::string;
using std::stringstream;

List::List() {
	first = 0;
	currentSize = 0;
}

IIterator* List::getIterator() {
	return new ListIterator(first);
}

void List::remove(ICollectible *iCollectible) {
	Node *aux = first, *ant = first;
	ICollectible *item;
	bool find = 0;
	while (aux != 0 && !find) {
		item = aux->getElement();
		if (item->same(iCollectible)) {
			find = 1;
			if ((ant == first) && (ant == aux)) {
				first = aux->getNext();
				aux->setNext(0);
				delete aux;
			} else {
				ant->setNext(aux->getNext());
				aux->setNext(0);
				delete aux;
			}
		} else {
			ant = aux;
			aux = aux->getNext();
		}
	}
	currentSize--;
}

int List::size() {
	return currentSize;
}

bool List::same(ICollectible * list){
	return this == list;
}

bool List::member(ICollectible *iCollectible) {
	bool ret = 0;
	Node *aux = first;
	ICollectible *item;
	while (aux != 0 && !ret) {
		item = aux->getElement();
		aux = aux->getNext();
		ret = item->same(iCollectible);
	}
	return ret;
}

bool List::isEmpty() {
	return first == 0;
}

void List::add(ICollectible *iCollectible) {
	Node *aux = new Node(iCollectible);
	aux->setNext(first);
	this->first = aux;
	currentSize++;
}

string List::toString() {
	stringstream out;
	string sret;
	//out << "->";
	IIterator *it = getIterator();
	while (it->hasCurrent()) {
		//out << " |" << it->current()->toString() << "|->";
		out << it->current()->toString() << endl;
		it->next();
	}
	delete it;
	//out << " [!]";
	out << endl;
	sret = out.str();
	return sret;
}

List::~List() {
	if (first != 0)
		delete first;
}
